/**
 * extract img desc and price from special site
 * 
 * @author shufenghua
 */

var FS = require('fs'),
	
	argv = process.argv,
	pageInfo = {'title' : '', 'price' : ''},
	
	timeout = 5000,
	timeoutListener,
	
	STATIC_DIR = '/kxc/static/',
	PIC_API_DIR = '/kxc/pic_api/',
	
	ErrNo = {
		'timeout' : -100,
		'invalidArgs' : -101,
		'envErr' : -102,
		'unknow' : -1
	};
	
// log uncaught exception
process.on('uncaughtException', errLog);

// timeout handler
timeoutListener = listenTimeout();
	
// check arguments length
if(argv.length < 4) {
	errLog('Arguments length less then 4(use: node jsdom <url> <htmlfile>)', ErrNo.invalidArgs);
}

// main process
var jsdom = require('jsdom'), // jsdom provider of browser enviroment
	html = FS.readFileSync(argv[3]).toString(), // read html page
	jquery = FS.readFileSync(STATIC_DIR + 'htdocs/js/core/jQuery.js').toString(), // read jquery source
	siteJs = getSiteJs(argv[2]); // get special site process js source

jsdom.env({
	html : html,
	src : [jquery, siteJs],
	done : function(errors, window) {
		window.__jipin_sitedata && (pageInfo = window.__jipin_sitedata);
		
		// output and log error
		if(!errors) {
			pageInfo.errno = 0;
			process.stdout.write(JSON.stringify(pageInfo));
		} else {
			errLog(JSON.stringify(errors), ErrNo.envErr);
		}
		
		// clear timeout listener
		clearTimeout(timeoutListener);
	}
});

/**
 * get special site process js source according to page url
 */
function getSiteJs(url) {
	var siteJs = null,
		clientSiteJsConf = JSON.parse(FS.readFileSync(PIC_API_DIR + 'data/clientsitejs.json').toString());

	for(var site in clientSiteJsConf) {
		if(clientSiteJsConf.hasOwnProperty(site)) {
			if(url.indexOf(site) !== -1) {
				var siteJsPath = STATIC_DIR + 'htdocs/js/client/jipin/' + clientSiteJsConf[site];
				siteJs = FS.readFileSync(siteJsPath).toString();
				break;
			}
		}
	}
	return siteJs;
}

/**
 * time out listner
 */
function listenTimeout() {
	return setTimeout(function() {
		errLog('Process time out.', ErrNo.timeout);
	}, timeout);
}

/**
 * log exception
 */
function errLog(e, errno) {
	
	errno = errno || ErrNo.unknow;
	
	var fd = FS.openSync('err.log', 'a');
	FS.writeSync(fd, (new Date()) + ': (' + errno + ') ' + e + '\n');
	FS.close(fd);
	
	// errno output
	pageInfo.errno = errno;
	
	// prevent empty stdout
	process.stdout.write(JSON.stringify(pageInfo));
	
	process.exit(0);
}